package com.ghost.librariandb;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DataProvider
{
	private static Connection _connection = null;
	private static boolean _databaseFound = false;
	private static final String DATABASE_PATH = "database.mb";
	
	public static Connection getConnection()
	{
		if (_connection == null)
		{
			File dataFile = new File(DATABASE_PATH);
			_databaseFound = dataFile.exists();
			
			try
			{
				Class.forName("org.sqlite.JDBC");
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				_connection = DriverManager.getConnection("jdbc:sqlite:" + DATABASE_PATH);
				Statement statement = _connection.createStatement();
				statement.setQueryTimeout(30);
				if (!_databaseFound)
				{
					System.out.println("Database not found!!");
					statement.executeUpdate("drop table if exists Member");
					statement.executeUpdate("create table Member (ID integer, Name string, DOB int, IDCardNumber string, Address string, PhoneNumber string, JoinDate int)");
					statement.executeUpdate("drop table if exists Book");
					statement.executeUpdate("create table Book (ID integer, Name string, Author string, Tags string, AddedDate int, BorrowerID int, BorrowedDate int, ReturnedDate int)");
					statement.close();
				}
				else
				{
					System.out.println("Database found.");
				}
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
		return _connection;
	}
	
	public static void closeConnection()
	{
		if (_connection != null)
		{
			try
			{
				_connection.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
			
			_connection = null;
		}
	}
}
